# coding=UTF-8
from django.core.mail import EmailMessage, SMTPConnection
from django.template import Context, Template
from django.conf import settings
from os.path import join

def load_template(template, context):
    signature = ''
    for dir in settings.TEMPLATE_DIRS:
        try:
            signature = open(join(dir, template), 'r').read()
            signature = Template(signature)
            signature = signature.render(Context(context))
        except Exception, e:
            print e
    return signature

def send_email(email_message):
    smtp = SMTPConnection(
        host          = settings.EMAIL_HOST,
        port          = settings.EMAIL_HOST_PORT,
        username      = settings.EMAIL_HOST_USERNAME,
        password      = settings.EMAIL_HOST_PASSWORD,
        use_tls       = settings.EMAIL_USE_TLS,
        fail_silently = settings.EMAIL_FAIL_SILENTLY
    )
    email_message.connection = smtp
    if smtp.open():
        smtp.send_messages([email_message])
        smtp.close()
        return True
    else:
        return False

def write_email(titulo, body, recipients=None):
    mail_subject = settings.EMAIL_SUBJECT_PREFIX + ' ' + titulo
    mail_body = body + load_template(settings.EMAIL_SIGNATURE_TEMPLATE, {})
    mail_from = settings.DEFAULT_FROM_EMAIL
    if recipients == None:
        mail_to = ['%(nombre)s <%(email)s>' % {'nombre': a[0], 'email': a[1]} \
                   for a in settings.ADMINS]
    else:
        recipient_type = type(recipients).__name__
        if recipient_type == 'list':
            mail_to = recipients
        elif recipient_type == 'unicode' or recipient_type == 'str':
            mail_to = [recipients]
        else:
            raise Exception
    return EmailMessage(mail_subject, mail_body, mail_from, mail_to)

def report_exception(request, exception):
    return send_email(
        redactar_email(
            'Exception: %s' % exception.__str__(),
            exception.__str__() + '\n' + request.__str__(),
            ['%(nombre)s <%(email)s>' % {'nombre': a[0], 'email': a[1]} \
             for a in settings.ADMINS]
        )
    )
